<?php

namespace Controller;

class TopicControllerOutput
{
	public $topicHTML = "";
	public $postHTML = "";
}


class TopicController
{
	//Parametrar: Instanser av klasserna Database, TopicList, TopicView samt LoginHandler
	//Retunerar HTML Sträng - visning och redigering av ett Topic med tillhörande Posts via "TopicControllerOutput"
	public function DoControll(\Model\Database $db, \Model\TopicList $tl, \View\TopicView $tv,  \Model\LoginHandler $lh)
	{
		//Skapar instanser	
		$plc = new \Controller\PostListController();
		
		//Hämtar det aktuella topic objektet	
		$topic = \View\NavigationView::getSelectedTopic($tl);

		$out = new TopicControllerOutput();
		
		if($topic == NULL)//Om anv skriver in ett TopicID som inte existerar i URL:en
		{
			$out->topicHTML = $tv->RenderMessage(\View\TopicView::TOPIC_DOESNT_EXIST);			
		}			
		else if($tv->TriedToDeleteTopic() == TRUE)
		{
			$tl->DeleteTopic($topic->getId());
			$out->topicHTML = $tv->RenderMessage(\View\TopicView::TOPIC_SUCCSESSFULLY_DELETED);	
		}			
		else if($tv->TriedToEditTopic() == TRUE)
		{
			$out->topicHTML = $tv->RenderEditTopicForm($topic);	
		}
		else if($tv->TriedToConfirmEdit() == TRUE)
		{
			//Anaropar valideringsfunktion
			$validationArray = $tl->ValidateTopicInput($tv->GetHeader(), $tv->GetContent());		
			
			//Retunerar felmeddelande om sådana finns
			if(empty($validationArray) == FALSE)
			{
				$out->topicHTML = $tv->RenderEditTopicForm($topic);	
				$out->topicHTML .= $tv->RenderErrorArray($validationArray);
				return $out;
			}			
			
			//Uppdaterar
			$tl->EditTopic($tv->GetHeader(), $tv->GetContent(), $topic->getId());
		    
		    //Hämtar det updaterade topicobjektet
		    $topic = \View\NavigationView::getSelectedTopic($tl);
						
			$out->topicHTML = $tv->RenderTopic($topic, $lh->GetUserIdBySession());
			$out->postHTML = $plc->DoControll($db, $lh, $topic);
		}
		//Annars sker endast en visning av topic objektet		
		else
		{
			$out->topicHTML = $tv->RenderTopic($topic, $lh->GetUserIdBySession());	
			$out->postHTML = $plc->DoControll($db, $lh, $topic);		
		}
			
		return $out;		
	}
}

?>